<?php
declare (strict_types = 1);

namespace app\user\controller;

use service\vo\user\User;
use thans\jwt\facade\JWTAuth;
use think\Exception;
use think\response\Json;

class Index extends Base
{
    //注册用户
    public function register(): Json
    {
        // 用户名
        $username = request()->post('username');
        // 密码
        $password = request()->post('password');
        //确认密码
        $confirmPassword  = request()->post('confirmPassword');

        try {
            if(empty($username)){
                throw new Exception("用户名不能为空");
            }
            if(empty($password)){
                throw new Exception("密码不能为空");
            }
            if(empty($confirmPassword)){
                throw new Exception("确认密码不能为空");
            }
            if($password != $confirmPassword){
                throw new Exception("两次密码输入不一致");
            }

            $user = new User();
            $user->setUsername($username);
            $user->setPassword($password);
            $user->setEmail("");
            $user->setPhone("");
            $id = $this->getUserService()->addUser($user);
            $returnArr = [
              "id" => $id,
            ];
            return $this->requestSuccessReturn($returnArr);
        } catch (Exception $e) {
            $data = $e->getData();
            $message = $e->getMessage();
            if(!empty($data['error']) && !empty($data['error']['data'])){
                $message = $data['error']['data'];
            }
            return $this->requestFailReturn($message, $e->getCode());
        }
    }

    //用户登录
    public function login(): Json
    {
        $username = request()->post('username');
        $password = request()->post('password');
        // 登录
        try {
            if (empty($username)) {
                throw new Exception("用户名不能为空");
            }

            if (empty($password)) {
                throw new Exception("密码不能为空");
            }

            // 判断用户登录
            $user = $this->getUserService()->login($username, $password);
            $jwtData = [
                'id' => $user->getId()
            ];
            $token = JWTAuth::builder($jwtData);

            $returnArr = [
                'token' => "bearer " . $token,
                'user' => [
                    'id' => $user->getId(),
                    'username' => $user->getUsername(),
                ]
            ];
            return $this->requestSuccessReturn($returnArr);

        } catch (Exception $e) {
            $data = $e->getData();
            $message = $e->getMessage();
            if(!empty($data['error']) && !empty($data['error']['data'])){
                $message = $data['error']['data'];
            }
            return $this->requestFailReturn($message, $e->getCode());
        }
    }
}
